<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="宽带套餐ID" prop="broadbandId">
        <el-input
          v-model="queryParams.broadbandId"
          placeholder="请输入宽带套餐ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="订单总金额" prop="totalPrice">
        <el-input
          v-model="queryParams.totalPrice"
          placeholder="请输入订单总金额"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ORDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付时间" prop="payTime">
        <el-date-picker
          v-model="queryParams.payTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="收货信息id" prop="addressId">
        <el-input
          v-model="queryParams.addressId"
          placeholder="请输入收货信息id"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="备注信息" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注信息"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="订单编号" align="center" prop="id" width="180" />
      <el-table-column label="套餐名称" align="center" prop="packageName" />
      <el-table-column label="宽带速率" align="center" prop="speed" />
      <el-table-column label="订单金额" align="center" prop="totalPrice">
        <template #default="scope">
          <span class="text-red-500">¥{{ scope.row.totalPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货信息" align="center" prop="addressInfo" min-width="200" />
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="支付时间"
        align="center"
        prop="payTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-dropdown>
            <el-button link type="primary">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-if="scope.row.status === 2"
                  @click="handleAssignInstall(scope.row)"
                >
                  分配安装
                </el-dropdown-item>
                <el-dropdown-item
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['order:update']"
                >
                  编辑
                </el-dropdown-item>
                <el-dropdown-item
                  @click="handleDelete(scope.row.id)"
                  v-hasPermi="['order:delete']"
                >
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OrderForm ref="formRef" @success="getList" />

  <!-- 分配安装弹窗 -->
  <el-dialog
    v-model="assignDialogVisible"
    title="分配安装"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="assignFormRef"
      :model="assignForm"
      :rules="assignRules"
      label-width="100px"
    >
      <el-form-item label="技术员" prop="technicianId">
        <el-select
          v-model="assignForm.technicianId"
          placeholder="请选择技术员"
          class="!w-100%"
        >
          <el-option
            v-for="item in technicianList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="assignDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleConfirmAssign" :loading="assignLoading">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { OrderApi, OrderVO } from '@/api/order'
import { getUsersByRole } from '@/api/system/user'
import { WorkOrderApi, WorkOrderVO } from '@/api/workOrder'
import OrderForm from './OrderForm.vue'
import { ArrowDown } from '@element-plus/icons-vue'

/** 订单信息 列表 */
defineOptions({ name: 'Order' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<OrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  broadbandId: undefined,
  totalPrice: undefined,
  status: undefined,
  payTime: [],
  addressId: undefined,
  remark: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const selectedOrder = ref<OrderVO>() // 当前选中的订单

const assignDialogVisible = ref(false)
const assignLoading = ref(false)
const technicianList = ref<{ id: number; nickname: string }[]>([])
const assignFormRef = ref()
const assignForm = reactive({
  technicianId: undefined
})
const assignRules = {
  technicianId: [{ required: true, message: '请选择技术员', trigger: 'change' }]
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderApi.getOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderApi.deleteOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrderApi.exportOrder(queryParams)
    download.excel(data, '订单信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 分配安装 */
const handleAssignInstall = async (row: OrderVO) => {
  try {
    // 获取技术员列表
    const data = await getUsersByRole(2)
    technicianList.value = data
    // 打开弹窗
    assignDialogVisible.value = true
    // 保存当前订单信息
    selectedOrder.value = row
  } catch (error) {
    message.error('获取技术员列表失败')
  }
}

/** 确认分配 */
const handleConfirmAssign = async () => {
  if (!assignFormRef.value) return
  await assignFormRef.value.validate()
  
  if (!selectedOrder.value) return
  
  assignLoading.value = true
  try {
    // 创建工单
    await WorkOrderApi.createWorkOrder({
      orderId: selectedOrder.value.id!,
      technicianId: assignForm.technicianId!,
      status: 1 // 待处理状态
    })
    
    // 更新订单状态为待安装
    await OrderApi.updateOrder({
      ...selectedOrder.value,
      status: 3 // 待安装状态
    })
    
    message.success('已分配安装')
    assignDialogVisible.value = false
    // 刷新列表
    getList()
  } catch (error) {
    message.error('分配安装失败')
  } finally {
    assignLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-form-item) {
  margin-right: 16px;
  margin-bottom: 15px;
}
</style>
